{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-11-24T12:36:56.964290Z",
     "start_time": "2025-11-24T12:36:56.721371Z"
    }
   },
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_absolute_error\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# 创建示例数据\n",
    "def create_sample_data():\n",
    "    np.random.seed(42)\n",
    "    n_samples = 1000\n",
    "\n",
    "    data = {\n",
    "        'brand': np.random.choice(['A', 'B', 'C', 'D'], n_samples),\n",
    "        'year': np.random.randint(2010, 2023, n_samples),\n",
    "        'mileage': np.random.randint(1000, 200000, n_samples),\n",
    "        'engine_size': np.random.uniform(1.0, 3.0, n_samples),\n",
    "        'fuel_type': np.random.choice(['Petrol', 'Diesel'], n_samples)\n",
    "    }\n",
    "\n",
    "    df = pd.DataFrame(data)\n",
    "\n",
    "    # 模拟价格计算\n",
    "    price = 50000 + \\\n",
    "            (df['brand'].map({'A': 10000, 'B': 5000, 'C': 0, 'D': -2000})) + \\\n",
    "            ((df['year'] - 2010) * 2000) + \\\n",
    "            (-df['mileage'] * 0.1) + \\\n",
    "            np.random.normal(0, 5000, n_samples)\n",
    "\n",
    "    df['price'] = price\n",
    "    return df\n",
    "\n",
    "# 数据预处理\n",
    "def preprocess_data(df):\n",
    "    df_processed = df.copy()\n",
    "\n",
    "    # 编码分类变量\n",
    "    categorical_cols = ['brand', 'fuel_type']\n",
    "    for col in categorical_cols:\n",
    "        le = LabelEncoder()\n",
    "        df_processed[col] = le.fit_transform(df_processed[col])\n",
    "\n",
    "    return df_processed\n",
    "\n",
    "# 主程序\n",
    "def main():\n",
    "    # 1. 加载数据\n",
    "    data = create_sample_data()\n",
    "    print(\"数据形状:\", data.shape)\n",
    "\n",
    "    # 2. 预处理\n",
    "    data_processed = preprocess_data(data)\n",
    "\n",
    "    # 3. 准备特征和目标\n",
    "    X = data_processed.drop('price', axis=1)\n",
    "    y = data_processed['price']\n",
    "\n",
    "    # 4. 分割数据\n",
    "    X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "    # 5. 训练模型\n",
    "    model = LinearRegression()\n",
    "    model.fit(X_train, y_train)\n",
    "\n",
    "    # 6. 预测和评估\n",
    "    y_pred = model.predict(X_val)\n",
    "    mae = mean_absolute_error(y_val, y_pred)\n",
    "\n",
    "    # 7. 输出结果\n",
    "    print(f\"验证集 MAE: {mae:.2f}\")\n",
    "    print(\"\\n特征重要性:\")\n",
    "    for feature, coef in zip(X.columns, model.coef_):\n",
    "        print(f\"{feature}: {coef:.2f}\")\n",
    "\n",
    "# 运行程序\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据形状: (1000, 6)\n",
      "验证集 MAE: 4351.89\n",
      "\n",
      "特征重要性:\n",
      "brand: -4206.31\n",
      "year: 2035.53\n",
      "mileage: -0.10\n",
      "engine_size: 365.83\n",
      "fuel_type: 529.16\n"
     ]
    }
   ],
   "execution_count": 1
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
